package com.dotstone.chipism.activity;


import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.EventBusEntity;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.OnDeviceStatusListener;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.SancePopWindow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LingHuoSwitchActivity extends BaseActivity {
    private boolean received = false;
    public static TextView tvTitle;
    private View btnBack;
    public static Button btn_switch3;
    public static Button btn_switch2;
    public static Button btn_switch1;
    public  Button btnAdd;
    private TextView mStatusBar;
    private int devicetype;
    private String deviceid;
    private int position;
    private List<Scene> list;
    private byte[] deviceAdd;
    private byte[] cmdData;
    private String address;
    private MySocket socket;
    private String maindeviceid;
    private int data1[] = new int[11];
    private byte buffer[] = new byte[11];
    byte[] bytes;
    byte[] data;
    int[] dataCmd;
    String cmd;
    private SVProgressHUD mSVProgressHUD;


    private boolean flag1=false;
    private boolean flag2=false;
    private boolean flag3=false;
    private int times=0;


    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.btn_switch1:
                if(devicetype==97){//  一键零火开关 只有2路开关有效  控制指令0x12     00H   关闭     FFH   打开
                    if(flag1){
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x12, (byte)00, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag1=false;
                        btn_switch1.setBackgroundResource(R.drawable.btn_pressed);
                       // btn_switch1.setText("关");
                    }else{
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x12, (byte) 0xFF, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag1=true;
                        btn_switch1.setBackgroundResource(R.drawable.btn);
                      //  btn_switch1.setText("开");
                    }
                }else  {//
                    if(flag1){
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x11, (byte)00, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag1=false;
                        btn_switch1.setBackgroundResource(R.drawable.btn_pressed);
                       // btn_switch1.setText("关");
                    }else{
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x11, (byte) 0xFF, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag1=true;
                        btn_switch1.setBackgroundResource(R.drawable.btn);
                     //   btn_switch1.setText("开");
                    }
                }

                break;
            case R.id.btn_switch2:
                if(devicetype==98){//  二键零火开关  只有1路和3路开关有效  控制指令0x12     00H   关闭     FFH   打开
                    if(flag2){
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x13, (byte)00, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=false;
                        btn_switch2.setBackgroundResource(R.drawable.btn_pressed);
                       // btn_switch2.setText("关");
                    }else{
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x13, (byte) 0xFF, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=true;
                        btn_switch2.setBackgroundResource(R.drawable.btn);
                      //  btn_switch2.setText("开");
                    }
                }else if(devicetype==99) {//
                    if(flag2){
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x12, (byte)00, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=false;
                        btn_switch2.setBackgroundResource(R.drawable.btn_pressed);
                      //  btn_switch2.setText("关");
                    }else{
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x12, (byte) 0xFF, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=true;
                        btn_switch2.setBackgroundResource(R.drawable.btn);
                       // btn_switch2.setText("开");
                    }
                }else{
                    if(flag2){
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x11, (byte)00, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=false;
                        btn_switch2.setBackgroundResource(R.drawable.btn_pressed);
                   //     btn_switch2.setText("关");
                    }else{
                        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x11, (byte) 0xFF, 0x00, 0x00};
                        data = getCmdData(bytes, address);
                        dataCmd = byte2HexStr(data);
                        cmd = transCmd(dataCmd);
                        sendCmd(cmd);
                        flag2=true;
                        btn_switch2.setBackgroundResource(R.drawable.btn);
                        //btn_switch2.setText("开");
                    }
                }
                break;
            case R.id.btn_switch3:
              //  三键零火开关
                if(flag3){
                    bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x13, (byte)00, 0x00, 0x00};
                    data = getCmdData(bytes, address);
                    dataCmd = byte2HexStr(data);
                    cmd = transCmd(dataCmd);
                    sendCmd(cmd);
                    flag3=false;
                    btn_switch3.setBackgroundResource(R.drawable.btn_pressed);
                   // btn_switch3.setText("关");
                }else{
                    bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x13, (byte) 0xFF, 0x00, 0x00};
                    data = getCmdData(bytes, address);
                    dataCmd = byte2HexStr(data);
                    cmd = transCmd(dataCmd);
                    sendCmd(cmd);
                    flag3=true;
                    btn_switch3.setBackgroundResource(R.drawable.btn);
                  //  btn_switch3.setText("开");
                }
                break;
            case R.id.nextstep:

                break;
            case R.id.back_layout:
                finish();
                break;
        }
    }

    private void sendCmd(String cmd) {

        if (socket.isLocalSuccess()) {
            Log.i("onResponse", "cmd:" + cmd);
            socket.sendMqttData(cmd);
        } else {
            Log.i("onResponse1", "cmd:" + cmd);
            SocketManager.getInstance().sendRemoteData(socket.getMac(), maindeviceid, cmd);
        }
    }

    private String transCmd(int data[]) {
        String sendStr = "";
        JSONObject jo = new JSONObject();
        JSONObject jo1 = new JSONObject();
        try {
            jo.put("a", "20000");
            jo.put("b", 0);
            jo.put("c", "20," + SocketManager.getInstance().user_id);
            jo.put("d", "10," + DeviceManager.getInstance().getmWlanId());
            jo.put("e", 1);
            jo.put("f", System.currentTimeMillis());
            jo.put("h", "0.0.1");
            jo1.put("cmd", 100);
            if (data != null && data.length != 0) {
                JSONArray ja = new JSONArray();
                for (int i = 0; i < data.length; i++) { // 依次将数组元素添加进JSONArray对象中
                    ja.put(data[i]);
                }
                jo1.put("data", ja);
            }
            jo.put("g", "" + jo1 + "");
            sendStr = jo.toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sendStr;
    }


    public static int[] byte2HexStr(byte[] b) {
        int[] cmd = new int[b.length];
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? stmp : stmp);
            sb.append(",");
            cmd[n] = Integer.parseInt(stmp, 16);
        }
        return cmd;
    }

    private byte[] getCmdData(byte[] commandData, String deviceAddress) {
        int CMDLENGTH = 10;
        deviceAdd = hexStringToBytes(deviceAddress);
        cmdData = new byte[CMDLENGTH];
        System.arraycopy(commandData, 0, cmdData, 0, CMDLENGTH);
        System.arraycopy(deviceAdd, 0, cmdData, 1, 5);
        return cmdData;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
         return R.layout.activity_linghuo_switch;
    }

    @Override
    public void initView(View view) {
        mSVProgressHUD = new SVProgressHUD(LingHuoSwitchActivity.this);
        btnBack = $(R.id.back_layout);
        tvTitle = $(R.id.title_tv);
        btnAdd = $(R.id.nextstep);
        mStatusBar = $(R.id.tv_statusBar_mian);
        btn_switch1 = $(R.id.btn_switch1);
        btn_switch2 = $(R.id.btn_switch2);
        btn_switch3 = $(R.id.btn_switch3);
        list=new ArrayList<>();
        devicetype = getIntent().getIntExtra("devicetype",97);
        deviceid=getIntent().getStringExtra("deviceid");
        address=getIntent().getStringExtra("address");
        maindeviceid=getIntent().getStringExtra("maindeviceid");
        socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
        if (socket == null) {
            ToastShow.Show(getApplicationContext(), "没有找到所绑定网关，无法控制该设备!");
            finish();
        }
        if(devicetype==97){
            btn_switch1.setVisibility(View.VISIBLE);
            btn_switch2.setVisibility(View.GONE);
            btn_switch3.setVisibility(View.GONE);
        }else  if(devicetype==98){
            btn_switch1.setVisibility(View.VISIBLE);
            btn_switch2.setVisibility(View.VISIBLE);
            btn_switch3.setVisibility(View.GONE);
        }  if(devicetype==99){
            btn_switch1.setVisibility(View.VISIBLE);
            btn_switch2.setVisibility(View.VISIBLE);
            btn_switch3.setVisibility(View.VISIBLE);
        }
        bytes = new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x20, (byte) 0x0, 0x00, 0x00};//查询开关状态
        data = getCmdData(bytes, address);
        dataCmd = byte2HexStr(data);
        cmd = transCmd(dataCmd);
        sendCmd(cmd);
        checkStatus();
        check();
        boolVersion();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void check() {
        times++;
        if (times<=3) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if(received==false){
                        check();
                    }else{
                        mHandler.sendEmptyMessage(211);
                        return;
                    }
                }
            }, 2 * 1000);
        } else {
            mHandler.sendEmptyMessage(666);//超时
        }
    }


    @Override
    public void setListener() {
        tvTitle.setText("零火开关");
       // btnAdd.setText("确定");
        btnAdd.setVisibility(View.GONE);
        btnBack.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btn_switch3.setOnClickListener(this);
        btn_switch2.setOnClickListener(this);
        btn_switch1.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {

    }




    public void boolVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            // getWindow().addFlags(
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
            layoutParams1.height = statusbarHeight;
            mStatusBar.setLayoutParams(layoutParams1);
            mStatusBar.setVisibility(View.VISIBLE);
        } else {
            mStatusBar.setVisibility(View.GONE);
        }
    }


    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            int[] status= (int[]) msg.obj;
            switch (msg.what) {
                case 211:
                    if (mSVProgressHUD.isShowing()) {
                        mSVProgressHUD.dismiss();
                    }
                    break;
                case 666:
                    if (mSVProgressHUD.isShowing()) {
                        mSVProgressHUD.dismiss();
                    }
                    ToastShow.Show(getApplicationContext(), "获取状态失败：连接超时或设备未通电");
                    break;
                case 1:
                    received = true;
                    if(status[0]==0){
                     //   btn_switch1.setText("关");
                        btn_switch1.setBackgroundResource(R.drawable.btn_pressed);
                        flag1=false;
                    }else if(status[0]==255){
                       // btn_switch1.setText("开");
                        btn_switch1.setBackgroundResource(R.drawable.btn);
                        flag1=true;
                    }
                    break;
                case 2:
                    received = true;
                    if(status[0]==0){
                      //  btn_switch1.setText("关");
                        btn_switch1.setBackgroundResource(R.drawable.btn_pressed);
                        flag1=false;
                    }else if(status[0]==255){
                      //  btn_switch1.setText("开");
                        btn_switch1.setBackgroundResource(R.drawable.btn);
                        flag1=true;
                    }
                    if(status[1]==0){
                      //  btn_switch2.setText("关");
                        btn_switch2.setBackgroundResource(R.drawable.btn_pressed);
                        flag2=false;
                    }else if(status[1]==255){
                        //btn_switch2.setText("开");
                        btn_switch2.setBackgroundResource(R.drawable.btn);
                        flag2=true;
                    }
                    break;
                case 3:
                    received = true;
                    if(status[0]==0){
                      //  btn_switch1.setText("关");
                        btn_switch1.setBackgroundResource(R.drawable.btn_pressed);
                        flag1=false;
                    }else if(status[0]==255){
                      //  btn_switch1.setText("开");
                        btn_switch1.setBackgroundResource(R.drawable.btn);
                        flag1=true;
                    }
                    if(status[1]==0){
                      //  btn_switch2.setText("关");
                        btn_switch2.setBackgroundResource(R.drawable.btn_pressed);
                        flag2=false;
                    }else if(status[1]==255){
                      //  btn_switch2.setText("开");
                        btn_switch2.setBackgroundResource(R.drawable.btn);
                        flag2=true;
                    }
                    if(status[2]==0){
                      //  btn_switch3.setText("关");
                        btn_switch3.setBackgroundResource(R.drawable.btn_pressed);
                        flag3=false;
                    }else if(status[2]==255){
                      //  btn_switch3.setText("开");
                        btn_switch3.setBackgroundResource(R.drawable.btn);
                        flag3=true;
                    }
                    break;
                default:
                    break;
            }
        }
    };


    public void checkStatus() {
        mSVProgressHUD.showWithStatus("正在获取设备状态");

        socket.setRecDataCallBackListener_Serach(new MySocket.RecDataCallBackListener_Serach() {

            @Override
            public void onReceiveData(String data) {
                // TODO Auto-generated method stub
                Log.e("wmy", "164 从mysocket获取插座状态");
              //  received = true;
                parseRecData(data);


            }
        });
        SocketManager.getInstance().setOnDeviceStatusListener(new OnDeviceStatusListener() {

            @Override
            public void onStatus(String data, int what) {
                // TODO Auto-generated method stub
                // mHandler.sendEmptyMessage(what);
                Log.e("wmy", "175插座收到返回数据" + data);
               // received = true;
             //   parseRecData1(data);
            }
        });
        //checkTimeout();

    }



    private void parseRecData(String data) {

        if (data.length() < 10 || data == null) {
            return;
        }
        JSONObject jo;
        // Log.i("wmy", "获取插座状态" + data);
        try {
            jo = new JSONObject(data);
            String a = jo.getString("a");
            Message msgMessage;
            if (a.equals("20000")) {
               int[] status= parseSwitchStatus(data,devicetype);
                if(status.length==1){//为一键零火开关

                     msgMessage = Message.obtain();
                    // 将需要传递到主线程的数据放到Message对象的obj属性中，以便于传递到主线程。
                    msgMessage.obj = status;
                    // Message对象的what属性是为了区别信息种类，而方便主线程中根据这些类别做相应的操作。
                    msgMessage.what = 1;
                    // handler对象携带着Message中的数据返回到主线程
                    mHandler.sendMessage(msgMessage);
                    // mHandler.sendEmptyMessage(1);
                }else if(status.length==2){//为二键零火开关

                    msgMessage = Message.obtain();
                    msgMessage.obj = status;
                    msgMessage.what = 2;
                    mHandler.sendMessage(msgMessage);
                }else if(status.length==3){//为三键零火开关

                    msgMessage = Message.obtain();
                    msgMessage.obj = status;
                    msgMessage.what = 3;
                    mHandler.sendMessage(msgMessage);
              }
            }

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }


    private int[] parseSwitchStatus(String data,int devicetype) {
        Log.i("wmy", "解析红外设备地址 = " + data);
        int type =0;
        int[] arr=new int[]{};
        try {
            JSONObject jo = new JSONObject(data);
            String g = jo.getString("g");
            JSONObject jo1 = new JSONObject(g);
            JSONArray ja = jo1.getJSONArray("data");

            if(devicetype==97){//一键开关  只有2路开关
                for (int i = 1; i < 9; i++) {
                    type = ja.getInt(8);
                    arr= new int[]{type};
                }
            }else if(devicetype==98){//二键开关  只有1路和3路开关
                for (int i = 1; i < 9; i++) {
                   // type = ja.getInt(8);
                    arr= new int[]{ja.getInt(7),ja.getInt(9)};
                }
            }else if(devicetype==99){
                for (int i = 1; i < 9; i++) {
                    type = ja.getInt(8);
                    arr= new int[]{ja.getInt(7),ja.getInt(8),ja.getInt(9)};
                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return arr;
    }

}
